import { db } from '@/lib/db';
import { httpClient } from '@/lib/http';
import { format, fromUnixTime } from 'date-fns';

const itemToNews = (item) => {
    // console.log(item, item.combination[-1]?.simpleModule?.bottomBar?.time);
    const newsId = item.info?.itemId;
    const isSimple = item.combination.length === 1;
    let newsTitle = '';
    let tm = 0;
    if (item.combination.length === 1) {
        newsTitle = item.combination[0].simpleModule.title;
        tm = item.combination[0].simpleModule.bottomBar.time;
    }
    if (item.combination.length === 2) {
        newsTitle = item.combination[0].title.content;
        const lastItem = item.combination[item.combination.length - 1];
        tm = lastItem.bottomBar.time;
    }
    if (item.combination.length >= 3) {
        newsTitle =
            item.combination[1]?.htmlAbstract?.content ||
            item.combination[1]?.title?.content ||
            item.combination[0]?.title?.content;
        const lastItem = item.combination[item.combination.length - 1];
        tm = lastItem.bottomBar.time;
    }
    const newsTimeObj = fromUnixTime(tm / 1000);
    const pattern = 'MM-dd HH:mm';
    const newsTime = format(newsTimeObj, pattern);
    // console.log(newsTitle, newsTimeObj, newsTime);
    const newsUrl = item.info?.jumpUrl;
    return {
        newsId,
        newsTitle,
        newsTime,
        newsUrl
    };
};

/**
 * 获取ths股票新闻
 * @param {string} secuCode 证券代码
 * @returns {Promise<Array>}
 */
export const getThsNews = async (secuCode) => {
    const marketCode = secuCode.startsWith('6') ? '17' : '33';
    const url = `https://m.10jqka.com.cn/app/timeline/v1/list?marketCode=${marketCode}&stockCode=${secuCode}`;
    const resp = await httpClient.get(url);
    const news = resp.data?.pageItems || [];
    const convtedNews = news.map((item) => itemToNews(item));
    // const sortedNews = convtedNews.sort((a, b) => b.newsTime - a.newsTime);
    return convtedNews;
};

export const getClsArticles = async () => {
    const articles = await db.$queryRaw`
        SELECT art_title,art_content FROM tb_article WHERE art_title not similar to '%(龙虎榜)%' AND created_at >= now()-'36 hours'::interval ORDER BY created_at desc   
    `;
    return articles;
};

export const getArticlesByBlocks = async (blocks) => {
    if (!blocks) return [];
    const blocks_reg = blocks.join('|');
    const articles = await db.$queryRaw`
        SELECT art_title,art_content,art_url,created_at FROM tb_article WHERE art_title ~* ${blocks_reg} AND created_at >= now()-'5 hours'::interval ORDER BY created_at desc   
    `;
    return articles;
};

export const getArticles = async () => {
    const articles = await db.$queryRaw`
        SELECT art_title,art_content,art_url,art_source,created_at 
        FROM tb_article
        WHERE 1=1 
            AND created_at >= now()-'12 hour'::interval
        ORDER BY created_at desc LIMIT 150
    `;
    return articles;
};

export const searchArticles = async (keyword) => {
    const articles = await db.$queryRaw`
        SELECT art_title,art_content,art_url,art_source,created_at 
        FROM tb_article
        WHERE 1=1 
            AND created_at >= now()-'2 days'::interval
            AND  art_title || ';' ||art_content ~* ${keyword}
        ORDER BY created_at desc LIMIT 150
    `;
    return articles;
};

export const searchArticlesBySecuName = async (secu_name) => {
    const articles = await db.$queryRaw`
        SELECT art_title,art_content,art_url,art_source,created_at 
        FROM tb_article
        WHERE 1=1 
            AND created_at >= now()-'12 hour'::interval
            AND  art_title || ';' ||art_content ~* ${secu_name}
        ORDER BY created_at desc LIMIT 15
    `;
    return articles;
};

export const searchArticlesByTokens = async (regTokenStr) => {
    if (!regTokenStr) return [];
    const articles = await db.$queryRaw`
        SELECT art_title,art_content,art_url,art_source,created_at 
        FROM tb_article
        WHERE 1=1 
            AND created_at >= now()-'12 hour'::interval
            AND  art_title ~* ${regTokenStr}
        ORDER BY created_at desc LIMIT 15
    `;
    return articles;
};
